module.exports = {
  onWillParseMarkdown: function(markdown) {
    
    function getDatas(datas, path) {
      if (!datas) {
        return;
      }
      for (let i = 0; i < datas.length; i++) {
        if (datas[i].name && datas[i].name === path) {
          return datas[i];
        }
      }
    }

    function postmanApiToDoc(path) {
      var fs = require('fs');

      var res = "";

      var arrPaths = path.split("#");
      if (arrPaths.length > 0) {
        var filePath = arrPaths[0];
        var isExists = fs.existsSync(filePath);
        if (isExists) {
          var datas = fs.readFileSync(filePath, "utf-8");
          datas = JSON.parse(datas);
          for (let i = 1; i < arrPaths.length; i++) {
            const path = arrPaths[i];
            datas = getDatas(datas.item, path);
            if (!datas) {
              break;
            }
            if (datas.request) {
              let request = datas.request;
              let method = request.method;
              let uri = "";
              let params = "";
              if (request.url && request.url.path) {
                uri = request.url.path.join('/')
              }
              if (request.url && request.url.query) {
                let query = request.url.query;
                for (let j = 0; j < query.length; j++) {
                  const p = query[j];
                  if (params.length > 0) {
                    params += "&";
                  }
                  params += p.key + "=" + p.value;
                }
              }
              res += `- ${method} ${uri}\r\n`;
              res += `- params: ${params}\r\n`;
              res += `- headers: ${method}\r\n`;
              res += `- body: ${method}\r\n`;
              res += `- response headers: ${method}\r\n`;
              res += `- response: ${method}\r\n`;
            }
            if (!datas.item) {
              break;
            }
          }
          // res += datas;
        }
      }
      return res;
    }

    return new Promise((resolve, reject)=> {

      var arrStrs = markdown.match(/\[postman_api\]\(.+\)/gm);
      if (arrStrs ) {
        for (let i = 0; i < arrStrs.length; i++) {
          const matchStr = arrStrs[i];
          var path = matchStr.substring(matchStr.indexOf("(")+1, matchStr.indexOf(")"));
          var apiDoc = postmanApiToDoc(path);
          markdown = markdown.replace(matchStr, apiDoc);
        }
      }
      console.log(markdown);

      return resolve(markdown)
    })
  },
  onDidParseMarkdown: function(html, {cheerio}) {
    return new Promise((resolve, reject)=> {
      return resolve(html)
    })
  },
  onWillTransformMarkdown: function (markdown) {
        return new Promise((resolve, reject) => {
            return resolve(markdown);
        });
    },
  onDidTransformMarkdown: function (markdown) {
      return new Promise((resolve, reject) => {
          return resolve(markdown);
      });
  }
}